'''
Author: duliang thinktanker@163.com
Date: 2025-08-07 15:07:56
LastEditors: duliang thinktanker@163.com
LastEditTime: 2025-08-19 10:55:31
FilePath: 
Description: 
'''
import psutil
import os
import time
from threading import Thread

# 获取当前进程
# process = psutil.Process(os.getpid())


def get_cpu_usage(process):
    # 获取当前进程的 CPU 百分比（调用一次后需间隔一段时间才有意义）
    # 先调用一次初始化（返回0）
    process.cpu_percent(interval=None)  # interval=None 表示与上次调用之间的差值
    cpu_sum = 0.0
    # 模拟一些计算任务
    # print("监控 CPU 使用中...")
    for i in range(10):
        # 一些 CPU 密集型操作（例如循环计算）
        # 获取当前 CPU 使用率
        cpu_usage = process.cpu_percent(interval=None)
        cpu_sum += cpu_usage
        # print(f"第 {i+1} 次: CPU 使用率 = {cpu_usage:.2f}%")
        time.sleep(0.1)
    # print(f"平均 CPU 使用率: {cpu_sum / 10:.2f}%")
    with open('./data/cpu_mem_data/cpu_usage.txt', 'w', encoding='utf8') as f:
        f.write(f"{cpu_sum / 10:.2f}%")


def get_memory_usage(process):
    memory_mb = process.memory_info().rss / 1024 / 1024
    with open('./data/cpu_mem_data/memory_usage.txt', 'w',
              encoding='utf8') as f:
        f.write(f"{memory_mb:.2f} MB")
    # print(f"当前内存使用: {memory_mb:.2f} MB")
    # time.sleep(10)


def check_cpu_memory(process):
    '''
    
    主函数，启动 CPU 和内存监控线程
    '''
    # get_memory_usage(process)
    print("启动 CPU 和内存监控线程")
    while 1:
        get_memory_usage(process)
        get_cpu_usage(process)
        time.sleep(10)


if __name__ == "__main__":
    process = psutil.Process(os.getpid())
    check_cpu_memory(process)
